<template>
  <div class="category-products">

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="products-content">
        <div class="product-list">
          <!-- 商品列表 -->
          <div
            class="product-item"
            v-for="product in products"
            :key="product.id"
            @click="viewProductDetail(product)"
          >
            <div class="product-image">
              <img :src="product.image" alt="商品图片" />
            </div>
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
            <div class="product-desc">{{ truncateText(product.description, 20) }}</div>
              <div class="product-bottom">
                <div class="product-points">{{ product.points }} 积分</div>
                <div class="product-stock">库存: {{ product.stock }}</div>
              </div>
            </div>
            <div class="product-actions">
              <van-button
                size="small"
                type="default"
                @click.stop="buyProduct(product)"
              >
                详情
              </van-button>
            </div>
          </div>

          <!-- 空状态 -->
          <div class="empty-state" v-if="products.length === 0">
            <div class="empty-icon">📦</div>
            <div class="empty-text">暂无商品</div>
            <div class="empty-desc">该分类下暂时没有商品</div>
          </div>
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script>
import { Button, Toast, Dialog, PullRefresh } from 'vant'

export default {
  name: 'CategoryProducts',
  components: {
    [Button.name]: Button,
    [PullRefresh.name]: PullRefresh
  },
  data() {
    return {
      categoryId: null,
      categoryName: '',
      products: [],
      currentStudent: null,
      refreshing: false
    }
  },
  created() {
    this.categoryId = this.$route.params.categoryId
    this.categoryName = this.$route.params.categoryName

    // 优先从路由参数获取学生信息，如果没有则从缓存中获取
    this.currentStudent = this.$route.params.studentInfo || this.getStudentInfoFromStorage()

    // 保存学生信息到缓存
    if (this.currentStudent) {
      this.saveStudentInfoToStorage(this.currentStudent)
    }

    // 设置页面来源标记，用于检测返回场景
    sessionStorage.setItem('fromCategoryProducts', 'true')

    // 添加页面加载日志
    console.log('分类商品页面加载:', {
      categoryId: this.categoryId,
      categoryName: this.categoryName,
      studentInfo: this.currentStudent,
      timestamp: new Date().toISOString()
    })

    this.loadProducts()
  },
  methods: {
    async loadProducts() {
      try {
        // 添加商品加载开始日志
        console.log('开始加载商品列表:', {
          categoryId: this.categoryId,
          studentInfo: this.currentStudent,
          timestamp: new Date().toISOString()
        })

        // 准备请求参数
        const params = {
          goodsType: this.categoryId, // 物品类型对应分类ID
        }

        // 如果存在学生信息，获取depId字段用于查询接口
        if (this.currentStudent) {
          // 直接从studentInfo集合中获取depId字段
          const depId = this.currentStudent.depId;

          if (depId) {
            params.depId = depId
            console.log('使用校区ID查询商品:', { depId })
          } else {
            console.warn('学生信息中未找到depId字段，将使用默认查询')
          }
        }

        // 调用接口获取商品列表
        const response = await this.$http.getGoodsList(params)

        if (response.data.code === 200 && response.data.result) {
          // 接口返回成功，使用接口数据
          this.products = response.data.result.map(item => ({
            id: item.id,
            name: item.goodsName,
            description: item.goodsDescription || '',
            points: item.goodsPoints || 0,
            stock: item.goodsNumber || 0,
            image: item.goodsImg || require('@/assets/shouqin.png'),
            originalPrice: item.goodsOriginalPrice,
            price: item.goodsPrice,
            state: item.goodsState,
            depId: item.depId,
            type: item.goodsType
          }))

          // 添加商品加载成功日志
          console.log('商品列表加载成功:', {
            categoryId: this.categoryId,
            productCount: this.products.length,
            timestamp: new Date().toISOString()
          })
        } else {
          // 接口返回失败，使用默认数据
          console.warn('接口返回失败，使用默认数据:', {
            categoryId: this.categoryId,
            responseCode: response.data.code,
            timestamp: new Date().toISOString()
          })
          this.useDefaultProducts()
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        // 接口调用失败，使用默认数据
        this.useDefaultProducts()
      }
    },

    useDefaultProducts() {
      // 没有默认商品数据，直接设置为空数组
      this.products = []
    },
    viewProductDetail(product) {
      // 跳转到商品详情页面
      this.$router.push({
        name: 'product-detail',
        params: {
          id: product.id,
          from: 'pointsMall',
          studentInfo: this.currentStudent
        }
      })
    },
    buyProduct(product) {
      // 跳转到商品详情页面
      this.$router.push({
        name: 'product-detail',
        params: {
          id: product.id,
          from: 'pointsMall',
          studentInfo: this.currentStudent
        }
      })
    },
    async onRefresh() {
      try {
        console.log('下拉刷新开始:', {
          categoryId: this.categoryId,
          timestamp: new Date().toISOString()
        })

        // 重新加载商品数据
        await this.loadProducts()

        // 刷新成功提示
        Toast.success('刷新成功')

        console.log('下拉刷新完成:', {
          categoryId: this.categoryId,
          productCount: this.products.length,
          timestamp: new Date().toISOString()
        })
      } catch (error) {
        console.error('下拉刷新失败:', error)
        Toast.fail('刷新失败')
      } finally {
        // 无论成功失败，都要停止刷新状态
        this.refreshing = false
      }
    },
    truncateText(text, maxLength) {
      if (!text) return ''
      if (text.length <= maxLength) return text
      return text.substring(0, maxLength) + '...'
    },
    goBack() {
      // 返回积分商城时传递标识参数，表示是从分类商品页面返回
      this.$router.push({
        name: 'pointsMall',
        params: {
          fromCategoryProducts: true
        }
      })
    },
    // 保存学生信息到缓存
    saveStudentInfoToStorage(studentInfo) {
      try {
        localStorage.setItem('currentStudentInfo', JSON.stringify(studentInfo))
        console.log('学生信息已保存到缓存:', studentInfo)
      } catch (error) {
        console.error('保存学生信息到缓存失败:', error)
      }
    },
    // 从缓存获取学生信息
    getStudentInfoFromStorage() {
      try {
        const studentInfo = localStorage.getItem('currentStudentInfo')
        if (studentInfo) {
          const parsedInfo = JSON.parse(studentInfo)
          console.log('从缓存获取学生信息:', parsedInfo)
          return parsedInfo
        }
      } catch (error) {
        console.error('从缓存获取学生信息失败:', error)
      }
      return null
    }
  }
}
</script>

<style lang="scss" scoped>
.category-products {
  width: 100%;
  height: 100%;
  background: #f6f8fc;

  .header {
    height: 44px;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #f0f0f0;
    position: relative;

    .nav-bar {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 15px;

      .nav-back {
        font-size: 18px;
        color: #333;
        cursor: pointer;
        font-weight: bold;
      }

      .nav-title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
      }

      .nav-placeholder {
        width: 18px;
      }
    }
  }

  .products-content {
    padding: 20px;

    .section-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
    }

    .product-list {
      .product-item {
        background: white;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .product-image {
          width: 60px;
          height: 60px;
          border-radius: 6px;
          overflow: hidden;
          margin-right: 15px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .product-info {
          flex: 1;

          .product-name {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
          }

          .product-desc {
            font-size: 12px;
            color: #999;
            margin-bottom: 8px;
          }

          .product-bottom {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .product-points {
              font-size: 14px;
              color: #FF6B6B;
              font-weight: bold;
            }

            .product-stock {
              font-size: 12px;
              color: #999;
            }
          }
        }

        .product-actions {
          margin-left: 10px;

          .van-button {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 16px;
            color: #666;
            font-size: 12px;
            font-weight: 500;
            padding: 4px 12px;
            height: auto;
            min-width: 50px;
            transition: all 0.3s ease;

            &:hover {
              background: #e9ecef;
              border-color: #dee2e6;
            }

            &:active {
              transform: scale(0.95);
            }

            &::before {
              display: none;
            }
          }
        }
      }

      .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #999;

        .empty-icon {
          font-size: 48px;
          margin-bottom: 16px;
        }

        .empty-text {
          font-size: 16px;
          font-weight: bold;
          margin-bottom: 8px;
          color: #666;
        }

        .empty-desc {
          font-size: 14px;
          color: #999;
        }
      }
    }
  }
}
</style>
